<template>
  <div>
    <PreloadImage />
    <PromptBox v-show="showPrompt" :promptMessage="promptMessage" />
    <main class="main" :class="{ blur: whetherBlur }">
      <el-alert
        :title="`请耐心等待⌛️，阅读即将于 ${READING_TIME} 开始`"
        type="success"
        :closable="false"
      >
      </el-alert>
      <div class="mask">
        <span class="title">
          <i class="el-icon-trophy"></i>
          悦读·宋庆龄
        </span>
      </div>
      <section class="info-panel">
        <div class="content">
          <el-input
            placeholder="请输入姓名"
            prefix-icon="el-icon-user"
            v-model="name"
          >
          </el-input>
          <el-input
            placeholder="请输入手机号"
            prefix-icon="el-icon-phone"
            v-model="mobile"
          >
          </el-input>
          <el-select v-model="team" placeholder="请选择团队">
            <el-option
              v-for="item in options"
              :key="item.teamId"
              :label="item.teamName"
              :value="item.teamId"
            >
            </el-option>
          </el-select>
          <p class="attention">
            个人参赛，请选择（无）否则取消参赛资格
          </p>
          <el-button round :disabled="flag" @click.native="submitUserInfo"
            >确认提交</el-button
          >
        </div>
      </section>
      <div class="help">
        <Icon name="question-circle" class="help-icon" />
        <router-link to="/rules">游戏规则</router-link>
      </div>
    </main>
    <router-view @showPromptBox="showPromptBox" />
  </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex';
import Icon from 'vue-awesome/components/Icon';
import ScrollMessage from '@/components/ScrollMessage';
import PromptBox from '@/components/PromptBox';
import BeginButton from '@/components/BeginButton';
import PreloadImage from '@/components/PreloadImage';
import { SET_USER_INFO, GET_USER_INFO } from '@/store/mutation-types';
import { getTeamInfo, saveUserInfo } from '@/api';

export default {
  name: 'HomePage',
  data() {
    return {
      name: '',
      mobile: '',
      options: [],
      team: undefined,
      flag: false, // 用于控制提交按钮是否disabled
      showPrompt: false,
      whetherBlur: false,
      promptMessage: '',
      trailerPrize: 0,
      messages: [],
    };
  },
  methods: {
    submitUserInfo() {
      if (
        !/^((13[0-9])|(14[5-9])|(15([0-3]|[5-9]))|(16[6-7])|(17[1-8])|(18[0-9])|(19[1|3])|(19[5|6])|(19[8|9]))\d{8}$/.test(
          this.mobile,
        )
      ) {
        this.$message({ type: 'warning', message: '手机号错误' });
        return;
      }
      saveUserInfo({
        username: this.name,
        mobile: this.mobile,
        teamId: this.team,
      }).then(({ data }) => {
        if (data.code === 0) {
          this.setUserInfo({
            username: this.name,
            mobile: this.mobile,
            teamId: this.team,
            userId: data.userId,
            token: data.token,
          });
          this.$message({ message: '报名登录成功' });
          if (+Date.now() < new Date(this.READING_TIME)) this.$router.replace('/rules');
          else if (+Date.now() < new Date(this.START_ANSWER_TIME)) this.$router.replace('/read');
          else if (+Date.now() < new Date(this.END_ANSWER_TIME)) this.$router.replace('/quiz');
          else this.$router.replace('/rank');
        } else {
          this.$message({ type: 'error', message: data.msg });
        }
      });
    },
    showPromptBox(msg) {
      if (msg === '') return;
      this.promptMessage = msg;
      this.showPrompt = true;
      clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        this.showPrompt = false;
      }, 2500);
    },
    ...mapMutations({
      setUserInfo: SET_USER_INFO,
      getUserInfo: GET_USER_INFO,
    }),
  },
  computed: {
    ...mapState([
      'username',
      'userMobile',
      'userTeamId',
      'userId',
      'token',
      'READING_TIME',
      'START_ANSWER_TIME',
      'END_ANSWER_TIME',
    ]),
  },
  watch: {},
  components: {
    Icon,
    ScrollMessage,
    PromptBox,
    BeginButton,
    PreloadImage,
  },
  created() {
    // getWXUserInfo().then(({ data }) => {
    //   this.setUserInfo(data);
    // });
    getTeamInfo().then(({ data }) => {
      this.options = data.page ? data.page.list : null;
    });
  },
  mounted() {
    this.getUserInfo();
    this.$nextTick(() => {
      this.name = this.username;
      this.mobile = this.userMobile;
      this.team = this.userTeamId;
    });
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss" src="./style.scss"></style>
